package com.thread.base;

import java.io.IOException;

/**
 * @author: 一个小菜逼
 * @Date: 2020/4/2
 * 三个线程循环打印A、B、C
 */
public class MyThreadBase01 {

    public static class ThreadPrint implements Runnable {

        public String name;
        public Object pre;
        public Object self;

        public ThreadPrint(String name, Object pre, Object self) {
            this.name = name;
            this.pre = pre;
            this.self = self;
        }

        public void run() {
            int count = 10;
            while (count > 0) {
                synchronized (pre) {
                    synchronized (self) {
                        System.out.println(name);
                        count--;
                        self.notifyAll();
                    }
                    try {
                        if (count == 0) {
                            pre.notifyAll();
                        } else {
                            pre.wait();
                        }
                    } catch (Exception e) {
                        e.fillInStackTrace();
                    }

                }
            }
        }
    }

    public static void main(String[] args) {
        //一个打印对象，两个锁对象
        Object a = new Object();
        Object b = new Object();
        Object c = new Object();
        //创建三个Runnable接口的实现类，分别进行初始化
        ThreadPrint a1 = new ThreadPrint("A", c, a);
        ThreadPrint b1 = new ThreadPrint("B", a, b);
        ThreadPrint c1 = new ThreadPrint("C", b, c);
        try {
            System.in.read();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //创建三个线程对象
        Thread threadA = new Thread(a1);
        Thread threadB = new Thread(b1);
        Thread threadC = new Thread(c1);
        //开启三个线程
        try {
            threadA.start();
            Thread.sleep(10);
            threadB.start();
            Thread.sleep(10);
            threadC.start();
            Thread.sleep(10);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
